//
//  EditGroupInfoViewController.m
//  Findif
//
//  Created by Mac on 2019/2/26.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "EditGroupInfoViewController.h"

@interface EditGroupInfoViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UIButton * imageViewButton;
@property (nonatomic, strong)UIView * topBackView;
@property (nonatomic, strong)UIView * bottomBackView;
@property (nonatomic, strong)UILabel * nameLabel;
@property (nonatomic, strong)UILabel * tagLabel;
@property (nonatomic, strong)UILabel * exploreLabel;
@property (nonatomic, weak)UIView * lineView;
@property (nonatomic, weak)UITextField * textFiled;
@property (nonatomic, weak)UITextView * textView;
@property (nonatomic, strong)UIButton * eatButton;
@property (nonatomic, strong)UIButton * playButton;
@property (nonatomic, strong)UIButton * sportsButton;
@property (nonatomic, strong)UIButton * travelButton;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, copy)NSString * img;
@property (nonatomic, strong)NSMutableArray * buttonArray;


@end

@implementation EditGroupInfoViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    self.buttonArray = [NSMutableArray array];
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupNav{
    
    self.title = @"编辑资料";
    
    UIButton * rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 15 * SCREENH6)];
    
    [rightButton setTitle:@"提交" forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(didFinishButton) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    UIBarButtonItem * rightBar = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    self.navigationItem.rightBarButtonItem = rightBar;
}

- (void)setupUI{
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
    
    UIButton * imageViewButton = [UIButton new];
    
    imageViewButton.backgroundColor = [UIColor lightGrayColor];
    [imageViewButton addTarget:self action:@selector(editGroupImageView) forControlEvents:UIControlEventTouchUpInside];
    
    self.imageViewButton = imageViewButton;
    
    [self.view addSubview:self.imageViewButton];
    
    self.topBackView = [self setupBackView];
    [self.view addSubview:self.topBackView];
    self.bottomBackView = [self setupBackView];
    [self.view addSubview:self.bottomBackView];
    
    self.nameLabel = [self setupLabelWith:@"社团名称"];
    [self.topBackView addSubview:self.nameLabel];
    self.tagLabel = [self setupLabelWith:@"社团标签"];
    [self.topBackView addSubview:self.tagLabel];
    self.exploreLabel = [self setupLabelWith:@"社团介绍"];
    [self.bottomBackView addSubview:self.exploreLabel];
    
    
    UITextField * textFiled = [[UITextField alloc] init];
    
    textFiled.borderStyle = UITextBorderStyleNone;
    //    textFiled.backgroundColor = [UIColor clearColor];
    //    textFiled.layer.borderColor = [[UIColor clearColor] CGColor];
    //设置光标颜色
    textFiled.tintColor = ZRBlackColor;
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0x909090);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入社团名字" attributes:attrs];
    textFiled.textColor = ZRBlackColor;
    //    textFiled.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //    //设置显示模式为永远显示(默认不显示)
    //    textFiled.leftViewMode = UITextFieldViewModeAlways;
    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.textAlignment = NSTextAlignmentRight;
    
    self.textFiled = textFiled;
    
    [self.topBackView addSubview:self.textFiled];
    
    // 创建textView
    UITextView *textView =[[UITextView alloc] init];
    textView.backgroundColor= ZRWhiteColor;
    textView.text = @"快来详细介绍你的社团吧，让更多的人了解你的社团";
    textView.font = [UIFont systemFontOfSize:14 * SCREENH6];
    textView.textColor = ColorWithRGB(0x909090);
    textView.delegate = self;
    textView.layer.cornerRadius = 5;
    textView.layer.borderColor = [ColorWithRGB(0xF4F5F6) CGColor];
    textView.layer.borderWidth = 1 * SCREENH6;
    textView.layer.masksToBounds = YES;
    
    self.textView = textView;
    [self.bottomBackView addSubview:self.textView];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    self.lineView = lineView;
    
    [self.topBackView addSubview:self.lineView];
    
    self.eatButton = [self setupButtonWithTitle:@" 吃喝 "];
    self.eatButton.tag = 1137;
    [self.topBackView addSubview:self.eatButton];
    self.playButton = [self setupButtonWithTitle:@" 玩乐 "];
    self.playButton.tag = 1138;
    [self.topBackView addSubview:self.playButton];
    self.sportsButton = [self setupButtonWithTitle:@" 运动 "];
    self.sportsButton.tag = 1139;
    [self.topBackView addSubview:self.sportsButton];
    self.travelButton = [self setupButtonWithTitle:@" 旅行 "];
    self.travelButton.tag = 1140;
    [self.topBackView addSubview:self.travelButton];
    
    [self.buttonArray addObject:self.eatButton];
    [self.buttonArray addObject:self.playButton];
    [self.buttonArray addObject:self.sportsButton];
    [self.buttonArray addObject:self.travelButton];
    
    if (self.dict) {
        
        self.textFiled.text = self.dict[@"group_name"];
        NSArray *array = [self.dict[@"group_category"] componentsSeparatedByString:@","];
        NSString * iconStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,self.dict[@"group_img"]];
        NSURL * iconUrl = [NSURL URLWithString:iconStr];
        [self.imageViewButton sd_setImageWithURL:iconUrl forState:UIControlStateNormal];
        
        for (NSString * name in array) {
            
            if ([name isEqualToString:@"1137"]) {
                
                self.eatButton.selected = YES;
            }else if ([name isEqualToString:@"1138"]){
                
                self.playButton.selected = YES;
            }else if ([name isEqualToString:@"1139"]){
                
                self.sportsButton.selected = YES;
            }else if ([name isEqualToString:@"1140"]){
                
                self.travelButton.selected = YES;
            }
        }
        
        if (self.dict[@"group_desc"]) {
            
            self.textView.text = self.dict[@"group_desc"];
        }
        
        self.img = self.dict[@"group_img"];
    }
}


- (void)viewDidLayoutSubviews{
    
    [self.imageViewButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(150 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(topHeight);
    }];
    
    [self.topBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.height.mas_equalTo(100 * SCREENH6);
        make.width.mas_equalTo(345 * SCREENH6);
        make.top.mas_equalTo(self.imageViewButton.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.topBackView);
        make.height.mas_equalTo(1 * SCREENH6);
        make.leading.mas_equalTo(self.topBackView).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.topBackView).offset(-15 * SCREENH6);
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.topBackView).offset(10 * SCREENH6);
        make.top.mas_equalTo(self.topBackView).offset(10 * SCREENH6);
    }];
    
    [self.textFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.nameLabel.mas_trailing).offset(10 * SCREENH6);
        make.trailing.mas_equalTo(self.topBackView).offset(-10 * SCREENH6);
        make.height.mas_equalTo(40 * SCREENH6);
        make.top.mas_equalTo(self.topBackView).offset(5 * SCREENH6);
    }];
    
    [self.tagLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.nameLabel);
        make.top.mas_equalTo(self.lineView.mas_bottom).offset(15 * SCREENH6);
    }];
    
    [self.eatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.tagLabel.mas_trailing).offset(30 * SCREENH6);
        make.centerY.mas_equalTo(self.tagLabel);
        make.height.mas_equalTo(20 * SCREENH6);
        make.width.mas_equalTo(50 * SCREENH6);
    }];
    
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.mas_equalTo(self.eatButton);
        make.leading.mas_equalTo(self.eatButton.mas_trailing).offset(10 * SCREENH6);
    }];
    
    [self.sportsButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.mas_equalTo(self.playButton);
        make.leading.mas_equalTo(self.playButton.mas_trailing).offset(10 * SCREENH6);
    }];
    
    [self.travelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.mas_equalTo(self.sportsButton);
        make.leading.mas_equalTo(self.sportsButton.mas_trailing).offset(10 * SCREENH6);
    }];
    
    [self.bottomBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.topBackView);
        make.height.mas_equalTo(250 * SCREENH6);
        make.top.mas_equalTo(self.topBackView.mas_bottom).offset(10 * SCREENH6);
    }];

    [self.exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.tagLabel);
        make.top.mas_equalTo(self.bottomBackView).offset(10 * SCREENH6);
    }];

    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.bottomBackView).offset(10 * SCREENH6);
        make.trailing.mas_equalTo(self.bottomBackView).offset(-10 * SCREENH6);
        make.bottom.mas_equalTo(self.bottomBackView);
        make.top.mas_equalTo(self.exploreLabel.mas_bottom).offset(7 * SCREENH6);
    }];
}


- (UIView *)setupBackView{
    
    UIView * view = [UIView new];
    
    view.backgroundColor = ZRWhiteColor;
    view.layer.cornerRadius = 5 * SCREENH6;
    view.layer.masksToBounds = YES;
    view.userInteractionEnabled = YES;
    
    return view;
}


- (UILabel *)setupLabelWith:(NSString *)title{
    
    UILabel * label = [UILabel new];
    
    label.text = title;
    label.textColor = ZRBlackColor;
    label.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    return label;
}


- (UIButton *)setupButtonWithTitle:(NSString *)title{
    
    UIButton * button = [UIButton new];
    
    button.adjustsImageWhenHighlighted = NO;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    //    UIImage *img = [self imageWithColor:[UIColor colorWithRed:207 green:207 blue:207 alpha:1]];
    [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0xCFCFCF)] forState:UIControlStateNormal];
    //    [button setBackgroundColor:[UIColor redColor]];
    [button addTarget:self action:@selector(clickTagButton:) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    button.layer.cornerRadius = 10 * SCREENH6;
    button.layer.masksToBounds = YES;
    if ([title isEqualToString:@" 吃喝 "]) {
        
        [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0xEB7664)] forState:UIControlStateSelected];
    }else if ([title isEqualToString:@" 玩乐 "]){
        
        [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0xAD77E9)] forState:UIControlStateSelected];
    }else if ([title isEqualToString:@" 运动 "]){
        
        [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0x72D9AA)] forState:UIControlStateSelected];
    }else if ([title isEqualToString:@" 旅行 "]){
        
        [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0x6AA3F1)] forState:UIControlStateSelected];
    }
    
    return button;
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

#pragma mark -实现图片选择器代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    NSString *base64Data = [frontImageData base64EncodedStringWithOptions:0];
    NSString * reslut = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",base64Data];
    
    
    [[ZRNetworkTool sharedTool] uploadOneImgResultWithImg:reslut WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            [self.imageViewButton setImage:image forState:UIControlStateNormal];
            self.img = [NSString stringWithFormat:@"%@",responseData[@"data"]];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
}

//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}




- (UIImage *)imageWithColor:(UIColor *)color
{
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    
    
    return image;
}


- (void)clickTagButton:(UIButton *)button{
    
   button.selected = !button.selected;
}


- (void)editGroupImageView{
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        
        self.alertVC.popoverPresentationController.sourceView = self.view;
        self.alertVC.popoverPresentationController.sourceRect = CGRectMake(10 * SCREENH6,kScreenH - 150 * SCREENH6,355 * SCREENH6,150 * SCREENH6);
        //            self.alertVC.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    [self presentViewController:self.alertVC animated:YES completion:nil];
}


- (void)didFinishButton{
    
    NSString * group_desc;
    
    if (self.textView.text && ![self.textView.text isEqualToString:@"快来详细介绍你的社团吧，让更多的人了解你的社团"]) {
        
        group_desc = self.textView.text;
    }
    
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:4];
    
    for (UIButton * button in self.buttonArray) {
        
        if (button.selected) {
            
            NSString * tag = [NSString stringWithFormat:@"%ld",button.tag];
            [array addObject:tag];
        }
    }
    
    NSString * group_category = [array componentsJoinedByString:@","];
    NSString * group_id = [NSString stringWithFormat:@"%@",self.dict[@"id"]];
    
    NSDictionary * dict = @{@"id":group_id,@"group_name":self.textFiled.text,@"group_img":self.img,@"group_category":group_category,@"group_desc":group_desc};
    
    [[ZRNetworkTool sharedTool] updateGroupWithDict:dict WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}


#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    if(textView.text.length < 1){
        textView.text = @"快来详细介绍你的社团吧，让更多的人了解你的社团";
        textView.textColor = ColorWithRGB(0xbebebe);
    }else{
        
        [textView resignFirstResponder];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"快来详细介绍你的社团吧，让更多的人了解你的社团"]){
        textView.text=@"";
        textView.textColor=[UIColor blackColor];
    }
}



@end
